from django.shortcuts import render, redirect
from app01 import models
from app01.models import Department, UserInfo, PrettyNum
from app01.utils.form import UserModelForm, PrettyModelForm, PrettyEditModelForm
from app01.utils.pageination_amd_search import Pagination
# Create your views here.
def user_list(request):


    queryset = UserInfo.objects.all()
    page_object = Pagination(request, queryset=queryset, pege_size=5)
    context = {
            'page_queryset': page_object.page_queryset,
            'page_string': page_object.html(),
    }

    return render(request, 'user_list.html', context)
def user_add(request):
    if request.method == 'GET':
        context = {
            'gender_choices': UserInfo.gender_choices,
            'department': Department.objects.all()
        }

        return render(request,
                      'user_add.html',
                      {'context': context})

    name = request.POST.get('name')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('account')
    create_time = request.POST.get('create_time')
    depart = request.POST.get('depart')
    gender = request.POST.get('gender')

    UserInfo.objects.create(
        name=name,
        password=pwd,
        age=age,
        account=account,
        create_time=create_time,
        depart_id=depart,
        gender=gender)
    return redirect("/user/list/")
def user_model_add(request):
    if request.method == 'GET':
        form = UserModelForm()
        return render(request,
                      'user_model_add.html',
                      {"form": form})
    # 数据校验 不允许为空
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    return render(request,
                  'user_model_add.html',
                  {'form': form})
def user_edit(request, nid):
    row_object = UserInfo.objects.filter(id=nid).first()
    if request.method == 'GET':
        # 获取默认值 根据ID去数据库获取要编辑的哪一行数据
        # row_object = UserInfo.objects.filter(id=nid).first()
        # 编辑功能 将编辑按钮传递的值传递给modelForm传递数据功能
        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {"form": form})

    # modelform接收POST请求数据 根据提交的信息将数据自动填充到输入框中
    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据，如果想要再用户输入以外增加一点值
        # form.instance.字段名 = 值
        # 注意更新和添加问题
        form.save()
    return redirect("/user/list/")
def user_delete(request, nid):
    """删除"""
    UserInfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")